package servlet;

import dao.RemarkDao;
import entity.Remark;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.SQLOutput;

@WebServlet("*.action")
public class ServletRemark extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        System.out.println("进入评论后台");
        //1、设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //2、拿到请求名
        String requestName = req.getRequestURI().substring(req.getRequestURI().lastIndexOf("/") + 1,
                req.getRequestURI().lastIndexOf("."));
        //3、根据不同的请求进行不同的逻辑派发
        if ("remark".equals(requestName)) {
            try {
                insert_remark_Service(req,resp);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        else
        {
//            RemarkDao remarkDao=new RemarkDao();
//            try {
//                req.setAttribute("remarks",remarkDao.findAll());
//                req.getRequestDispatcher("gbook.jsp").forward(req,resp);
//            } catch (SQLException throwables) {
//                throwables.printStackTrace();
//            }
        }


    }

    private void insert_remark_Service(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException {
        System.out.println("进入评论插入数据库");
        RemarkDao remarkDao=new RemarkDao();
        String username = req.getParameter("username");
        int noteid=Integer.parseInt(req.getParameter("noteid"));
        String remarktext=req.getParameter("remarktext");
        String remarkdate=req.getParameter("remarkdate");

        int remarkzan=Integer.parseInt(req.getParameter("remarkzan")) ;

        Remark remark=new Remark();
        System.out.println(remark.toString());

        remark.setUsername( username );
        remark.setRemarktext(remarktext);
        remark.setRemarkdate(remarkdate);
        remark.setRemarkzan(remarkzan);
        remark.setNoteid(noteid);
        boolean flag=remarkDao.insertRemark(remark);

        System.out.println(flag);
        PrintWriter writer = resp.getWriter();
        if(flag)
        {

            writer.write("评论成功");
        }
        else
        {
            writer.write("评论失败");
        }

    }

}
